import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { BusinessProductAListEntity } from '../../entity/product/a_list';
import { BusinessProductABatchEntity } from '../../entity/product/a_batch';
import * as _ from 'lodash';
import { CacheManager } from '@midwayjs/cache';
import { Context } from '@midwayjs/koa';

/**
 * business模块-产品-A-开始
 */
@Provide()
export class BusinessProductAStartService extends BaseService {
  @InjectEntityModel(BusinessProductAListEntity)
  businessProductAListEntity: Repository<BusinessProductAListEntity>;

  @InjectEntityModel(BusinessProductABatchEntity)
  businessProductABatchEntity: Repository<BusinessProductABatchEntity>;

  @Inject()
  cacheManager: CacheManager;

  @Inject()
  ctx: Context;

  /**
   * 录入
   * @param param
   */
  async enter(param) {
    const { userId } = this.ctx.admin;
    let productData = param.data;
    if (!(productData.length > 0)) {
      throw new CoolCommException('录入失败，请检查录入数据是否有误！');
    }
    const batchData = await this.createBatch({ userId });
    const batchId = batchData.id;
    const productNoArr = await this.generateProductNo({
      userId,
      batchId,
      count: productData.length,
    });
    productData = productData.map((item, index) => {
      delete item.id;
      delete item.code;
      delete item.key;
      delete item.createTime;
      delete item.updateTime;
      item.code = productNoArr[index];
      item.userId = userId;
      item.batchId = batchId;
      item.printStatus = 0
      item.status = 0
      return item;
    });
    // 保存
    const result = await this.businessProductAListEntity.save(productData);
    // 更新批次数据
    await this.updateBatch({
      batchId,
      startNo: productNoArr[0],
      endNo: productNoArr[productNoArr.length - 1],
      count: productData.length,
    });
    return result;
  }

  /**
   * 生成产品编号
   */
  async generateProductNo({ userId, batchId, count }) {
    let serialNo = 0;
    // 根据用户ID、批次ID获取最后一次录入的产品信息
    const productData = await this.businessProductAListEntity
      .createQueryBuilder()
      .where('userId = :userId && batchId = :batchId', { userId, batchId })
      .orderBy('createTime', 'DESC')
      .getOne();
    if (productData) {
      serialNo = Number(productData.code.split('S')[1]);
    }
    // 应用标识
    const appValue = 1;
    // 用户标识
    const userValue = userId;
    // 产品标识
    const productValue = 1;
    // 批次标识
    const batchValue = batchId;
    // 流水号
    let serialValue = serialNo;
    const resData = [];
    for (let index = 0; index < count; index++) {
      serialValue = serialValue + 1;
      resData.push(
        `A${appValue}U${userValue}P${productValue}B${batchValue}S${serialValue}`
      );
    }
    return resData;
  }

  /**
   * 创建录入批次
   */
  async createBatch({ userId }) {
    const batchNo = await this.generateBatchNo({ userId });
    const data = {
      batchNo,
      userId,
    };
    return await this.businessProductABatchEntity.save(data);
  }
  /**
   * 更新录入批次数据
   */
  async updateBatch({ batchId, startNo, endNo, count }) {
    const result = await this.businessProductABatchEntity.save({
      id: batchId,
      startNo,
      endNo,
      count,
    });
    return result;
  }
  /**
   * 生成录入批次编号
   */
  async generateBatchNo({ userId }) {
    let serialNo = 0;
    // 根据用户ID获取最后一次录入的批号
    const batchData = await this.businessProductABatchEntity
      .createQueryBuilder()
      .where('userId = :userId', { userId })
      .orderBy('createTime', 'DESC')
      .getOne();
    if (batchData) {
      serialNo = Number(batchData.batchNo.split('S')[1]);
    }
    // 应用标识
    const appValue = 1;
    // 用户标识
    const userValue = userId;
    // 产品标识
    const productValue = 1;
    // 流水号
    const serialValue = serialNo + 1;
    return `A${appValue}U${userValue}P${productValue}S${serialValue}`;
  }
  /**
   * 更新打印状态
   */
  async updatePrintStatus(ids, status) {
    const { userId } = this.ctx.admin;
    const result = await this.businessProductAListEntity
      .createQueryBuilder()
      .update({ printStatus: status })
      .where({ "userId": userId, "id": In(ids) })
      .execute();
    return result
  }
}
